/**
 * Created by Administrator on 2018/6/1 0001.
 */
const Auth = require('../model/auth.model')
const AuthInfo = require('../model/authInfo.model')
const config = require('../config')
const Redis = require('../units/redis')
const {handleError, handleSuccess} = require("../units/handle")
const JWT = require('jsonwebtoken')
const crypto = require('crypto')

//密码md5加密
const md5Decode = (pwd) => {
    return crypto.createHash("md5").update(pwd).digest('hex')
}

class AuthController {
    static async getAuth(ctx) {
        const all = await Auth.find().catch(e => {
            throw (500, "服务器内部错误")
        })
        if (all) {
            handleSuccess({ctx, data: all})
        } else {
            handleError({ctx, message: "未有注册账号"})
        }
    }

    static async login(ctx) {
        console.log(ctx.request.body)
        const {username, password} = ctx.request.body;
        const auth = await Auth.findOne({username: {'$in': username}, password: {'$in': password}}).catch(err => {
            throw (500, "服务器内部错误")
        })
        if (auth) {
            const user = await AuthInfo.findOne({user_id: auth._id})
                .catch(err => {
                    console.log(e)
                })
            if (user) {

                await Redis.setVal(auth._id, auth._id)
                handleSuccess({ctx, message: "登陆成功", data: {user, token: auth._id}})
            } else {
                handleSuccess({ctx, message: "登陆成功", data: user})
            }

        } else {
            handleError({ctx, message: "账号或密码错误"})
        }
    }
    static async logout(ctx){
        const token = ctx.header.authorization;
        if(token){
            const clear = await Redis.delVal(token)
            if(clear){
                handleSuccess({ctx, message: "退出成功"})
            }else{
                handleError({ctx, message: "退出失败"})
            }
        }
        handleError({ctx, message: "退出失败"})
    }
    static async resgister(ctx) {
        const {username} = ctx.request.body;
        const data = await Auth.findOne({username}).catch(err => {
            console.log(err)
        })
        if (data) {
            handleError({ctx, message: "账号已注册"})
        } else {
            const res = new Auth(ctx.request.body)
                .save()
                .catch(err => {
                    console.log(err)
                })
            if (res) {
                handleSuccess({ctx, message: "注册成功"})
            } else {
                handleError({ctx, message: "注册失败"})
            }
        }
    }
}
module.exports = AuthController